package swu.cx.roomwords

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import android.widget.Switch
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class MyAdapter(var useCardView:Boolean,val wordViewModel: MyViewModel): RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
    var allWords:List<Word> = listOf()
    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        val num: TextView = itemView.findViewById(R.id.num)
        val english: TextView = itemView.findViewById(R.id.EnglishText)
        val chinese: TextView = itemView.findViewById(R.id.MeaningText)
        @SuppressLint("UseSwitchCompatOrMaterialCode")
        val switchChineseMeaning: Switch = itemView.findViewById(R.id.switchMeaning)
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view = if(useCardView) {
            LayoutInflater.from(parent.context).inflate(R.layout.cell_card_layout, parent, false)
        }else{
            LayoutInflater.from(parent.context).inflate(R.layout.cell_normal_layout, parent, false)
        }
        val holder = MyViewHolder(view)
        holder.itemView.setOnClickListener {
            Intent().apply {
                val uri = Uri.parse("https://m.youdao.com/dict?le=eng&q="+holder.english.text)
                action = Intent.ACTION_VIEW
                data = uri
            }.also { holder.itemView.context.startActivity(it) }
        }
        holder.switchChineseMeaning.setOnCheckedChangeListener{ compoundButton: CompoundButton, isChecked: Boolean ->
            val word = holder.itemView.getTag(R.id.card_word) as Word
            if (isChecked){
                holder.chinese.visibility = View.GONE
                word.chineseInVisible = true
                wordViewModel.modify(word)
            }else{
                holder.chinese.visibility = View.VISIBLE
                word.chineseInVisible = false
                wordViewModel.modify(word)
            }
        }
        return holder
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val word = allWords[position]
        holder.itemView.setTag(R.id.card_word,word)
        holder.num.text = (position + 1).toString()
        holder.english.text = word.word
        holder.chinese.text = word.meaning
        if (word.chineseInVisible){
            holder.chinese.visibility = View.GONE
            holder.switchChineseMeaning.isChecked = true
        }else{
            holder.chinese.visibility = View.VISIBLE
            holder.switchChineseMeaning.isChecked = false
        }

    }

    override fun getItemCount(): Int {
        return allWords.size
    }

}